<?php
session_start();

if (!isset($_SESSION['username'])) {
    header("Location: ../login.php");
    exit();
}
include 'config.php';
// 数据库配置
header('Content-Type: application/json');

// 数据库配置

// 检查是否是 GET 请求
if ($_SERVER["REQUEST_METHOD"] == "GET") {
    // 获取 GET 数据
    $qq = $_GET['qq'] ?? '';
    $lxqq = $_GET['lxqq'] ?? '';
    $type = $_GET['type'] ?? ''; // 获取授权类型
    $ty = $_GET['ty'] ?? ''; // 获取ty值
    $now_time = time();

    // 检查授权类型和ty是否存在
    if (empty($type) || empty($qq) || empty($ty)) {
        $response = [
            "code" => "400",
            "msg" => "授权类型、QQ号和ty不能为空"
        ];
    } else {
        // 计算VIP时间
        $vip_time_duration = $type == 1 ? 2592000 : ($type == 2 ? 31536000 : 999999999999); // 1为月卡30天，2为年卡365天，其他为0
        $vip_time = $now_time + $vip_time_duration;

        // 检查是否已经存在该qq的记录
        $checkStmt = $conn->prepare("SELECT * FROM sq WHERE qq = ?");
        $checkStmt->bind_param("s", $qq);
        $checkStmt->execute();
        $result = $checkStmt->GET_result();
        $row = $result->fetch_assoc();

        if ($row) {
            // 如果存在，检查lxqq是否一致
            if ($row['lxqq'] != $lxqq) {
                $response = [
                    "code" => "500",
                    "msg" => "授权失败，lxqq不一致"
                ];
            } else {
                // 更新vip_time和ty
                $updateStmt = $conn->prepare("UPDATE sq SET vip_time = vip_time + ?, ty = ? WHERE qq = ?");
                $updateStmt->bind_param("isi", $vip_time_duration, $ty, $qq);
                if ($updateStmt->execute()) {
                    $vip_time = $now_time + $row['vip_time'] + $vip_time_duration;
                    $response = [
                        "code" => "200",
                        "msg" => "授权成功",
                        "vip_time" => $vip_time
                    ];
                } else {
                    $response = [
                        "code" => "500",
                        "msg" => "授权失败",
                        "error" => $updateStmt->error
                    ];
                }
            }
        } else {
            // 如果不存在，插入新的记录
            $insertStmt = $conn->prepare("INSERT INTO sq (qq, lxqq, now_time, vip_time, ty) VALUES (?, ?, ?, ?, ?)");
            $insertStmt->bind_param("ssiii", $qq, $lxqq, $now_time, $vip_time, $ty);
            if ($insertStmt->execute()) {
                $response = [
                    "code" => "200",
                    "msg" => "授权成功".$type,
                    "vip_time" => $vip_time
                ];
            } else {
                $response = [
                    "code" => "500",
                    "msg" => "授权失败",
                    "error" => $insertStmt->error
                ];
            }
        }
    }

    // 返回 JSON 响应
    echo json_encode($response, JSON_UNESCAPED_UNICODE);
} else {
    // 如果不是 GET 请求，返回错误
    header("HTTP/1.1 405 Method Not Allowed");
    exit("仅支持 GET 请求");
}

// 关闭数据库连接
$conn->close();
?>